using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Text;
using WeatherSystem.API.Data;
using WeatherSystem.API.Helpers;
using WeatherSystem.API.Models;
using WeatherSystem.API.Services;

namespace WeatherSystem.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    // [Authorize] // 已注释，后续可重新启用
    public class StatisticsController : ControllerBase
    {
        private readonly WeatherDbContext _context;
        private readonly IStatisticsService _statisticsService;
        private readonly ILogger<StatisticsController> _logger;
        private readonly ICacheService _cacheService;

        public StatisticsController(
            WeatherDbContext context,
            IStatisticsService statisticsService,
            ILogger<StatisticsController> logger,
            ICacheService cacheService)
        {
            _context = context;
            _statisticsService = statisticsService;
            _logger = logger;
            _cacheService = cacheService;
        }

        /// <summary>
        /// 获取城市天气统计数据（动态EAV结构）
        /// </summary>
        [HttpGet("city/{cityId}")]
        public async Task<ActionResult<Dictionary<string, object>>> GetCityStatistics(
            Guid cityId,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            try
            {
                var end = endDate ?? DateTime.UtcNow;
                var start = startDate ?? end.AddDays(-30);

                var statistics = await _statisticsService.GetCityStatisticsAsync(
                    cityId, start, end);

                if (statistics == null)
                {
                    return NotFound(new { message = "未找到该城市的统计数据" });
                }

                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取城市统计数据时发生错误: CityId={CityId}", cityId);
                return StatusCode(500, new { message = "获取统计数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取多城市对比统计（动态EAV结构）
        /// </summary>
        [HttpPost("compare")]
        public async Task<ActionResult<List<Dictionary<string, object>>>> CompareCities(
            [FromBody] CityComparisonRequest request)
        {
            try
            {
                if (request.CityIds == null || !request.CityIds.Any())
                {
                    return BadRequest(new { message = "请至少选择一个城市" });
                }

                if (request.CityIds.Count > 10)
                {
                    return BadRequest(new { message = "最多只能同时对比10个城市" });
                }

                var comparisonData = await _statisticsService.GetCityComparisonAsync(
                    request.CityIds, request.StartDate ?? DateTime.Today);

                return Ok(comparisonData);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "城市对比统计时发生错误");
                return StatusCode(500, new { message = "获取对比数据失败", error = ex.Message });
            }
        }


        /// <summary>
        /// 获取天气趋势数据（动态EAV结构）
        /// </summary>
        [HttpGet("trend/{cityId}")]
        public async Task<ActionResult<object>> GetWeatherTrend(
            Guid cityId,
            [FromQuery] int days = 7)
        {
            try
            {
                if (days < 1 || days > 365)
                {
                    return BadRequest(new { message = "天数范围应在1-365之间" });
                }

                var trendData = await _statisticsService.GetWeatherTrendAsync(cityId, days);
                return Ok(trendData);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气趋势数据时发生错误: CityId={CityId}", cityId);
                return StatusCode(500, new { message = "获取趋势数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 导出统计数据为CSV（动态EAV结构）
        /// </summary>
        [HttpGet("export/csv/{cityId}")]
        public async Task<IActionResult> ExportToCsv(
            Guid cityId,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            try
            {
                var end = endDate ?? DateTime.UtcNow;
                var start = startDate ?? end.AddDays(-30);

                var city = await _context.Cities.FindAsync(cityId);
                if (city == null)
                {
                    return NotFound(new { message = $"城市ID {cityId} 不存在" });
                }

                var weatherDataEntries = await _context.WeatherDataEntries
                    .Include(w => w.Metrics)
                    .ThenInclude(m => m.Definition)
                    .Where(w => w.CityId == cityId && w.RecordedAt >= start && w.RecordedAt <= end)
                    .OrderBy(w => w.RecordedAt)
                    .ToListAsync();

                var csv = GenerateDynamicCsv(weatherDataEntries, city.Name);
                var fileName = $"weather_data_{city.Name}_{start:yyyyMMdd}_{end:yyyyMMdd}.csv";

                return File(System.Text.Encoding.UTF8.GetBytes(csv), "text/csv", fileName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出CSV时发生错误: CityId={CityId}", cityId);
                return StatusCode(500, new { message = "导出数据时发生错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取系统统计概览（动态EAV结构）
        /// </summary>
        [HttpGet("overview")]
        public async Task<ActionResult<Dictionary<string, object>>> GetSystemOverview()
        {
            try
            {
                var totalCities = await _context.Cities.CountAsync();
                var totalWeatherRecords = await _context.WeatherDataEntries.CountAsync();
                var totalUsers = await _context.Users.CountAsync();
                
                var lastWeekStart = DateTime.UtcNow.AddDays(-7);
                var recentRecords = await _context.WeatherDataEntries
                    .Where(w => w.RecordedAt >= lastWeekStart)
                    .CountAsync();

                var lastDataCollection = await _context.DataCollectionLogs
                    .OrderByDescending(l => l.ExecutionTime)
                    .FirstOrDefaultAsync();

                var activeCities = await _context.WeatherDataEntries
                    .Where(w => w.RecordedAt >= lastWeekStart)
                    .Select(w => w.CityId)
                    .Distinct()
                    .CountAsync();

                var response = new Dictionary<string, object>
                {
                    ["totalCities"] = totalCities,
                    ["totalWeatherRecords"] = totalWeatherRecords,
                    ["totalUsers"] = totalUsers,
                    ["recentRecords"] = recentRecords,
                    ["activeCities"] = activeCities,
                    ["lastDataCollection"] = lastDataCollection?.ExecutionTime,
                    ["lastCollectionStatus"] = lastDataCollection?.Status ?? "未知"
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统概览时发生错误");
                return StatusCode(500, new { message = "获取系统概览时发生错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 生成动态CSV内容（EAV结构）
        /// </summary>
        private string GenerateDynamicCsv(List<WeatherDataEntry> weatherDataEntries, string cityName)
        {
            if (!weatherDataEntries.Any())
                return "";

            var allMetricKeys = weatherDataEntries
                .SelectMany(w => w.Metrics)
                .Select(m => m.MetricKey)
                .Distinct()
                .OrderBy(k => k)
                .ToList();

            var headerColumns = new List<string> { "RecordedAt", "Source" };
            headerColumns.AddRange(allMetricKeys);
            
            var csv = new StringBuilder();
            csv.AppendLine($"# Weather Data Export for {cityName}");
            csv.AppendLine($"# Generated: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC");
            csv.AppendLine(string.Join(",", headerColumns));

            foreach (var entry in weatherDataEntries)
            {
                var row = new List<string>
                {
                    entry.RecordedAt.ToString("yyyy-MM-dd HH:mm:ss"),
                    entry.Source ?? ""
                };

                foreach (var metricKey in allMetricKeys)
                {
                    var metric = entry.Metrics.FirstOrDefault(m => m.MetricKey == metricKey);
                    row.Add(metric?.RawValue ?? "");
                }

                csv.AppendLine(string.Join(",", row));
            }

            return csv.ToString();
        }
    }

    public class CityComparisonRequest
    {
        public List<Guid> CityIds { get; set; } = new();
        public DateTime? StartDate { get; set; }
        public DateTime? EndDate { get; set; }
    }
}